package com.liangtian.mdm.util;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.net.ftp.FTPReply;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.SocketException;

/**
 * Created by admin on 2017/9/26.
 */
public class FileUtil {
    private static Logger log = LoggerFactory.getLogger(FileUtil.class);
    private static String LOCAL_CHARSET = "GBK";
    private static String SERVER_CHARSET = "ISO-8859-1";

    private static FTPClient getconnectFtp(String url, int port, String username, String password) {
        FTPClient ftp = new FTPClient();
        int reply;
        try {
            ftp.connect(url, port);//连接FTP服务器
            ftp.login(username, password);//登录
            if (FTPReply.isPositiveCompletion(ftp.sendCommand(
                    "OPTS UTF8", "ON"))) {// 开启服务器对UTF-8的支持，如果服务器支持就用UTF-8编码，否则就使用本地编码（GBK）.
                LOCAL_CHARSET = "UTF-8";
            }
            ftp.setControlEncoding(LOCAL_CHARSET);
            ftp.setFileType(FTPClient.BINARY_FILE_TYPE);
            ftp.enterLocalPassiveMode();// 设置被动模式
            reply = ftp.getReplyCode();
            if (!FTPReply.isPositiveCompletion(reply)) {
                ftp.disconnect();
                log.error("连接ftp服务器出错");
            }
        } catch (IOException e) {
            log.error("连接ftp服务器出错");
            e.printStackTrace();
        }
        return ftp;
    }

    /**
     * 下载文件ftp
     *
     * @param url
     * @param port
     * @param username
     * @param password
     * @param remotePath
     * @param fileName
     * @return
     */
    public static boolean ftpDownFile(String url, int port, String username, String password, String remotePath, String fileName, OutputStream is) {
        boolean success = false;
        FTPClient ftp = getconnectFtp(url, port, username, password);
        try {

            ftp.changeWorkingDirectory(remotePath);//转移到FTP服务器目录
            FTPFile[] fs = ftp.listFiles();
            for (FTPFile ff : fs) {
                if (ff.getName().equals(fileName)) {
                    success = ftp.retrieveFile(ff.getName(), is);
                }
            }
            ftp.logout();

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (ftp.isConnected()) {
                try {
                    ftp.disconnect();
                } catch (IOException ioe) {
                }
            }
        }
        return success;
    }

    /**
     * 上传文件
     *
     * @param url
     * @param port
     * @param username
     * @param password
     * @param path
     * @param filename
     * @param input
     * @return
     */
    public static boolean ftpUploadFile(String url, int port, String username, String password, String path, String filename, InputStream input) {
        boolean success = false;
        FTPClient ftp = getconnectFtp(url, port, username, password);
        try {
            //递归建立文件夹
            String[] mkds = path.split("/");
            String curpath = "";
            boolean mkdFlag = false;
            boolean changeDirectoryFlag = false;
            for (int i = 0; i < mkds.length - 1; i++) {
                if (mkds[i] != null && mkds[i] != "") {
                    mkdFlag = ftp.makeDirectory(new String(mkds[i].getBytes(LOCAL_CHARSET), SERVER_CHARSET));
                    if (mkdFlag) {
                        log.info("目录创建成功!");
                    } else {
                        log.info("目录已经存在.");
                    }
                    changeDirectoryFlag = ftp.changeWorkingDirectory(new String(mkds[i].getBytes(LOCAL_CHARSET), SERVER_CHARSET));
                    if (changeDirectoryFlag) {
                        log.info("当前目录[" + mkds[i] + "].");
                    } else {
                        log.error("切换目录失败.");
                    }
                }
            }
            success = ftp.storeFile(new String(filename.getBytes(LOCAL_CHARSET), SERVER_CHARSET), input);
            input.close();
            ftp.logout();
        } catch (SocketException e1) {
            log.error("创建文件出错", e1);
        } catch (IOException e) {
            log.error("创建文件出错", e);
        } finally {
            if (ftp.isConnected()) {
                try {
                    ftp.logout();
                    ftp.disconnect();
                } catch (IOException ioe) {
                }
            }
        }
        return success;
    }

    public static boolean ftpDeleteFile(String url, int port, String username, String password, String path) {
        boolean success = false;
        try {
            FTPClient ftp = getconnectFtp(url, port, username, password);
            String curDirectory = ftp.printWorkingDirectory();
            if (StringUtils.isEmpty(curDirectory)) {// 若为空,则定位到根目录
                curDirectory = "";
            }
            String[] pathstres = path.split("/");

            // 删除文件
            boolean flag = ftp.changeWorkingDirectory(new String(path.substring(0, path.lastIndexOf("/")).getBytes(LOCAL_CHARSET), SERVER_CHARSET));// 转移到FTP服务器目录
            flag = ftp.deleteFile(new String(pathstres[pathstres.length - 1].getBytes(LOCAL_CHARSET), SERVER_CHARSET));
            if (!flag) {
                log.error("删除文件失败");
            }

            // 删除文件夹
            flag = ftp.changeToParentDirectory();
            success = ftp.removeDirectory(new String(pathstres[pathstres.length - 2].getBytes(LOCAL_CHARSET), SERVER_CHARSET));
            ftp.logout();
            ftp.disconnect();
        } catch (IOException e) {
            e.printStackTrace();
        }

        return success;

    }

}
